import React, { useState, useEffect } from 'react';
import { 
  Row, 
  Col, 
  Card, 
  Statistic, 
  Table, 
  DatePicker, 
  Select,
  Button,
  Spin,
  message 
} from 'antd';
import { 
  BarChartOutlined, 
  LineChartOutlined, 
  PieChartOutlined,
  DownloadOutlined,
  FileExcelOutlined
} from '@ant-design/icons';
import api from '../services/api';

const { RangePicker } = DatePicker;
const { Option } = Select;

const ReportsPage = () => {
  const [loading, setLoading] = useState(false);
  const [statsData, setStatsData] = useState({
    totalIssues: 0,
    resolvedIssues: 0,
    pendingIssues: 0,
    avgResolutionTime: 0
  });
  const [reportData, setReportData] = useState([]);
  const [reportType, setReportType] = useState('issue');
  const [dateRange, setDateRange] = useState([]);

  // 获取统计数据
  const fetchStats = async () => {
    setLoading(true);
    try {
      // 构建查询参数
      const params = {};
      if (dateRange.length === 2) {
        params.start_date = dateRange[0].format('YYYY-MM-DD');
        params.end_date = dateRange[1].format('YYYY-MM-DD');
      }
      
      // 获取统计数据
      try {
        const statsResponse = await api.get('/reports/stats', { params });
        setStatsData(statsResponse.data);
      } catch (statsError) {
        console.log('统计API不可用，使用模拟数据:', statsError);
        const mockStats = {
          total_issues: 156,
          resolved_issues: 98,
          pending_issues: 58,
          avg_resolution_time: 2.5
        };
        setStatsData({
          totalIssues: mockStats.total_issues,
          resolvedIssues: mockStats.resolved_issues,
          pendingIssues: mockStats.pending_issues,
          avgResolutionTime: mockStats.avg_resolution_time
        });
      }
      
      // 获取报表数据
      try {
        const reportEndpoint = reportType === 'issue' ? '/reports/issues' : 
                              reportType === 'case' ? '/reports/cases' : '/reports/users';
        const reportResponse = await api.get(reportEndpoint, { params });
        setReportData(reportResponse.data);
      } catch (reportError) {
        console.log('报表API不可用，使用模拟数据:', reportError);
        const mockReportData = [
          {
            key: '1',
            date: '2023-12-01',
            category: '硬件',
            count: 12,
            resolved: 8,
            resolution_rate: '66.7%'
          },
          {
            key: '2',
            date: '2023-12-02',
            category: '软件',
            count: 18,
            resolved: 15,
            resolution_rate: '83.3%'
          },
          {
            key: '3',
            date: '2023-12-03',
            category: '固件',
            count: 8,
            resolved: 6,
            resolution_rate: '75.0%'
          }
        ];
        setReportData(mockReportData);
      }
    } catch (error) {
      console.error('获取统计数据失败:', error);
      message.error('获取统计数据失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchStats();
  }, [reportType, dateRange]);

  const handleExport = async () => {
    try {
      // 构建查询参数
      const params = { report_type: reportType };
      if (dateRange.length === 2) {
        params.start_date = dateRange[0].format('YYYY-MM-DD');
        params.end_date = dateRange[1].format('YYYY-MM-DD');
      }
      
      // 调用导出API
      const response = await api.get('/reports/export', {
        params,
        responseType: 'blob' // 重要：设置响应类型为blob
      });
      
      // 创建下载链接
      const blob = new Blob([response.data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      });
      
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      
      // 设置文件名
      const filename = reportType === 'issue' ? '问题报表.xlsx' : 
                      reportType === 'case' ? '案例报表.xlsx' : '用户报表.xlsx';
      link.download = filename;
      
      // 触发下载
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      // 清理URL
      window.URL.revokeObjectURL(url);
      
      message.success(`${filename}导出成功`);
    } catch (error) {
      console.error('导出失败:', error);
      if (error.response?.status === 404) {
        message.error('没有找到数据，无法导出');
      } else {
        message.error('导出失败，请稍后再试');
      }
    }
  };

  const getColumns = () => {
    const baseColumns = [
      {
        title: '日期',
        dataIndex: 'date',
        key: 'date',
      },
      {
        title: '分类',
        dataIndex: 'category',
        key: 'category',
      }
    ];
    
    if (reportType === 'issue') {
      return [
        ...baseColumns,
        {
          title: '问题数量',
          dataIndex: 'count',
          key: 'count',
        },
        {
          title: '已解决',
          dataIndex: 'resolved',
          key: 'resolved',
        },
        {
          title: '解决率',
          dataIndex: 'resolution_rate',
          key: 'resolution_rate',
        }
      ];
    } else if (reportType === 'case') {
      return [
        ...baseColumns,
        {
          title: '案例数量',
          dataIndex: 'count',
          key: 'count',
        },
        {
          title: '已审核',
          dataIndex: 'approved',
          key: 'approved',
        },
        {
          title: '审核率',
          dataIndex: 'approval_rate',
          key: 'approval_rate',
        }
      ];
    } else {
      // 用户报表
      return [
        {
          title: '用户名',
          dataIndex: 'username',
          key: 'username',
        },
        {
          title: '创建问题数',
          dataIndex: 'issues_created',
          key: 'issues_created',
        }
      ];
    }
  };

  const columns = getColumns();

  return (
    <div>
      <h2>统计报表</h2>
      
      {/* 统计概览 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总问题数"
              value={statsData.totalIssues}
              prefix={<BarChartOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="已解决"
              value={statsData.resolvedIssues}
              prefix={<LineChartOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="待处理"
              value={statsData.pendingIssues}
              prefix={<PieChartOutlined />}
              valueStyle={{ color: '#fa8c16' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="平均解决时间"
              value={statsData.avgResolutionTime}
              suffix="天"
              prefix={<BarChartOutlined />}
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
      </Row>
      
      {/* 报表筛选 */}
      <Card style={{ marginBottom: 16 }}>
        <Row gutter={16} align="middle">
          <Col span={4}>
            <Select
              value={reportType}
              onChange={setReportType}
              style={{ width: '100%' }}
            >
              <Option value="issue">问题报表</Option>
              <Option value="case">案例报表</Option>
              <Option value="user">用户报表</Option>
            </Select>
          </Col>
          <Col span={6}>
            <RangePicker 
              style={{ width: '100%' }} 
              value={dateRange}
              onChange={setDateRange}
            />
          </Col>
          <Col span={4}>
            <Button type="primary" onClick={fetchStats}>
              查询
            </Button>
          </Col>
          <Col span={4} offset={6}>
            <Button 
              type="default" 
              icon={<FileExcelOutlined />}
              onClick={handleExport}
            >
              导出Excel
            </Button>
          </Col>
        </Row>
      </Card>
      
      {/* 报表数据 */}
      <Card title="报表数据">
        <Spin spinning={loading}>
          <Table 
            columns={columns} 
            dataSource={reportData}
            pagination={{
              total: reportData.length,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total, range) => 
                `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
            }}
          />
        </Spin>
      </Card>
    </div>
  );
};

export default ReportsPage;